<template>
  <div class="modify-dialog">
    <slot>
      <el-button size="small" type="primary" @click="showDialog()">
        新增套件
      </el-button>
    </slot>
    <el-dialog
      :close-on-click-modal="false"
      :title="modify === 'add' ? '新增' : '编辑'"
      width="500px"
      :visible.sync="dialogVisible"
    >
      <Form
        :form="form"
        @submit="submit"
        ref="form"
        labelWidth="100px"
        :inline="false"
        labelPosition="top"
      >
        <template #formBtn>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirm"> 确 定 </el-button>
          </div>
        </template>
      </Form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      modify: "add",
      dialogVisible: false,
      row: {},
      form: {
        name: {
          tag: "el-input",
          label: "套件名称",
          value: "",
          props: {
            clearable: true,
            placeholder: "请输入套件名称",
          },
        },
        salePrice: {
          tag: "el-input-number",
          label: "套件价格",
          value: "",
          props: {
            min: 0,
            precision: 2,
            clearable: true,
            placeholder: "请输入套件价格",
          },
        },
        // status: {
        // 	tag: "el-select",
        // 	label: "状态",
        // 	value: 1,
        // 	items: [
        // 		{ label: "停用", value: 0 },
        // 		{ label: "启用", value: 1 },
        // 	],
        // },
      },
    };
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.form.name.value = "";
      }
    },
  },
  methods: {
    confirm() {
      const form = this.$refs.form;
      form.submit();
    },
    submitDoneMsg() {
      this.dialogVisible = false;
      this.$emit("change");
    },
    submit(form) {
      const { modify, row } = this;
      form.status = 1;
      if (modify === "add")
        this.$api.addDirectory(form).then(this.submitDoneMsg);
      else if (modify === "edit") {
        this.$api
          .patchDirectory({ ...form, id: row.id })
          .then(this.submitDoneMsg);
      }
    },
    showDialog(modify = "add", row = {}) {
      this.dialogVisible = true;
      this.row = row;
      this.modify = modify || "add";
      for (const key in this.form) {
        let defValue = "";
        if (Array.isArray(this.form[key].value)) defValue = [];
        if (Object.hasOwnProperty.call(row, key))
          this.form[key].value = row[key] || defValue;
        else this.form[key].value = defValue;
      }
    },
  },
};
</script>

<style lang="less" scoped></style>
